/**
 * 业户信息
 */
var iFrameName = this.name;
$(function(){
	Enterprise.init();
	window.parent.global.ajaxLoading.close(1000);
});
var Enterprise = {
	init: function(){
		Enterprise.initAreaTreesExtend();
		Enterprise.initBusinessScopeList();
		Enterprise.initPlatformList();
		Enterprise.chooses ="";
		Enterprise.sub_url ="";
		Enterprise.queryW();
		Enterprise.initEvent();
		Enterprise.initEnterpriseList();
		placeholders("#enterpriseNameSql");
	},
	queryW : function(){
		var winW = $('body').width();
		$('.querys').width(winW);
	},
	initEvent: function(){
		
		$("#queryBtn").click(function(){
			Enterprise.queryEnterprise();
		});
		
		$("a[name='addEnterpriseBtn']").click(function(){
			var url = appCtx + "base/enterprise/initEnterpriseForm.html";
			window.parent.doDataDialog("insert","新增业户",iFrameName,"EnterpriseForm.saveEnterprise()", "Enterprise.EnterpriseListReload()",url);
		});
		
		$("a[name='updateEnterpriseBtn']").click(function(){
			Enterprise.updateEnterprise();
		});
		
		$("a[name='delEnterpriseBtn']").click(function(){
			Enterprise.delEnterprises();
		});
		
		$("a[name='exportEnterpriseBtn']").click(function(){
			Enterprise.exportEnterprise();
		});
		
		$("a[name='queryDetailBtn']").click(function(){
			Enterprise.queryDetailForm();
		});
		
		$("a[name='cogradientInfoBtn']").click(function(){
			Enterprise.synOwner();
		});
		
	},
    /**
     * 获取区域列表
     */
    initAreaTreesExtend: function () {
    	var areaTool =$('#queryArea').combotree({
			url:appCtx + "/system/common/queryAreaTree.html",
			valueField: 'id',
            textField: 'text',
            method: 'post',
            editable : true,
            collapseAll : true,
            onSuccess : function(data){
            },            
            loadFilter: function(data){
            	 data.unshift({ id: '', text: '所属区域', selected: "selected" });
                 return data;
    		},
/*    		onBeforeSelect:function(node){
    			 rows = node.children; 
    			  if(rows.length>1){
    				  $("#queryArea").tree("unselect");
    			  } 
    		  }, */
    		onLoadSuccess: function (data) {
    			$('#queryArea').combotree('tree').tree("collapseAll");
    			$('#queryArea').combotree('setValue','0')
         	}
			
		});
		areaTool.combogrid('textbox').keyup(function(event) {
			$('#queryArea').combotree('tree').tree("search", $(this).val());
		});
	},
    /**
     * 获取接入平台列表
     */
    initPlatformList: function () {
        $.ajax({
            type: 'post',
            url: appCtx + "/base/enterprise/loadPlatformList.html?time="+ new Date().getTime(),
            cache: false,
            dataType: "JSON",
            success: function (data) {	
    			if(data){		
    				var selectStr="";
    				selectStr+="<option value=''>接入平台</option>";
    				$.each(data,function(entryIndex,entry) {
    					selectStr+="<option value='"+entry.platformId+"'>"+entry.platformName+"</option>";
    				});
    				
    				$('#platform').html(selectStr);
    				
    				$("#platform").select2();
    				$("#platform").next().css("border","none");
    			}
            }
        });
        
    },
    /**
     * 获取经营范围列表
     */
    initBusinessScopeList: function () {
        $.ajax({
            type: 'post',
            url: appCtx + "/base/enterprise/loadBizScopeList.html?time="+ new Date().getTime(),
            cache: false,
            dataType: "JSON",
            success: function (data) {			
    			if(data){		
    				$('#businessScopeList').html("<select class='userInput fl' id='businessScopeListSql'></select>");				
    				var selectStr="";
    				selectStr+="<option value=''>经营范围</option>";
    				$.each(data,function(entryIndex,entry) {
    					selectStr+="<option value='"+entry.id+"'>"+entry.biz_name+"</option>";
    				});
    				
    				$('#businessScopeListSql').html(selectStr);
    				
    				$("#businessScopeListSql").select2();
    				$("#businessScopeListSql").next().css("border","none");
    			}
            }
        });
    },
     getTogetherTime : function (start,end){
    	 var startTime = Enterprise.getSimpleTime(start);
    	 var endTime = Enterprise.getSimpleTime(end);
    	 if (endTime && startTime) {
    		 return startTime+" 至 "+endTime;
		}
    	 return "";
     },
     getSimpleTime : function (time){
		   var outTime = "";
		   if ( time != "undefined") {
			  	var date = new Date(parseInt(time)); 
			    var y = date.getFullYear();    
			    var m = date.getMonth() + 1;    
			    m = m < 10 ? ('0' + m) : m;    
			    var d = date.getDate();    
			    d = d < 10 ? ('0' + d) : d;     
			    outTime = y + '-' + m + '-' + d;
	  	  	}
	  	  return outTime;
	    },
     getFromatTime : function (time){
		   var outTime = "0";
	  if (null != time && undefined != time ) {
		  	var date = new Date(parseInt(time));
		    var y = date.getFullYear();    
		    var m = date.getMonth() + 1;    
		    m = m < 10 ? ('0' + m) : m;    
		    var d = date.getDate();    
		    d = d < 10 ? ('0' + d) : d;    
		    var h = date.getHours();  
		    h = h < 10 ? ('0' + h) : h;  
		    var minute = date.getMinutes();  
		    var second = date.getSeconds();  
		    minute = minute < 10 ? ('0' + minute) : minute;    
		    second = second < 10 ? ('0' + second) : second;   
		    outTime = y + '-' + m + '-' + d+'  '+h+':'+minute+':'+second;
	  	  	}
	  	  return outTime;
	    },
    initEnterpriseList: function(){
		$("#tbEnterprise").flexigrid({
			url : appCtx + "/base/enterprise/loadEnterpriseList.html?time="+ new Date().getTime(),
			dataType : 'json',
			colModel : Enterprise.getColumn(),
			resizable : false,
			sortname : "id",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true
			minheight: 30, //列的最小高度
			nowrap: true, //是否不换行
			showToggleBtn : false,
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
			 rpOptions: [10, 20, 50, 100, 200], // 每页结果数
			checkbox : true,// 是否要多选框,默认为false。
			rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : false,
			width : $(".queryTable").width(),
			height : nav.whiceH[0]-157,
		});
	},
    getColumn: function(){
		return [{
			display : '业户ID',
			name : 'id',
			sortable : true,
			hide:true,
		},{
			display : '业户名称',
			name : 'name',
			width : 260,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '所属区域',
			name : 'areaName',
			width : 240,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '接入平台',
			name : 'platformName',
			width : 245,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '经营许可证号',
			name : 'bizLicenseNum',
			width : 120,
			sortable : false,
			showTitle:true,
			align : 'left'
		},{
			display : '签发机关',
			name : 'lssuingAuth',
			width : 150,
			sortable : false,
			showTitle:true,
			align : 'left'
		},{
			display : '证件有效日期',
			name : 'invalidTime',
			width : 170,
			sortable : false,
			showTitle:true,
			align : 'left',
			paramcolnames : [ 'invalidStartTime','invalidEndTime' ],
			handlefunction : Enterprise.getTogetherTime
		},{
			display : '经营范围',
			name : 'bizScope',
			width : 90,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '经济类型',
			name : 'economy_type_name',
			width : 90,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '联系人',
			name : 'contact',
			width : 75,
			sortable : false,
			align : 'left'
		},{
			display : '联系号码',
			name : 'phone',
			width : 90,
			sortable : false,
			align : 'left'
		},{
			display : '短息提醒',
			name : 'enableSms',
			width : 75,
			sortable : false,
			align : 'left',
			paramcolnames : ['enable_sms'],
			handlefunction : function(enable_sms){
				var str = "";
				if (!isNaN(enable_sms)) {
					str = enable_sms==1? "启用":"停用";
				}
				else{
					str="停用";
				}
				return str;
			}
		},{
			display : '联系邮箱',
			name : 'email',
			width : 120,
			sortable : false,
			align : 'left',
			showTitle:true
		},{
			display : '邮箱提醒',
			name : 'enableEmail',
			width : 75,
			sortable : false,
			align : 'left',
			paramcolnames : ['enable_email'],
			handlefunction : function(enable_email){
				var str = "";
				if (!isNaN(enable_email)) {
					str = enable_email==1? "启用":"停用";
				}
				else{
					str="停用";
				}
				return str;
			}
		},{
			display : '法人代表',
			name : 'corporate',
			width : 75,
			sortable : false,
			align : 'left'
		},{
			display : '同步运政信息',
			name : 'hasSync',
			width : 100,
			sortable : false,
			align : 'left',
			paramcolnames : ['has_sync'],
			handlefunction : function(has_sync){
				var str = "";
				if (!isNaN(has_sync)) {
					str = has_sync==1? "已同步":"未同步";
				}
				else{
					str="未同步";
				}
				return str;
			}
/*		},{
			display : '信息采集系统编码',
			name : 'sysPwd',
			width : 110,
			sortable : false,
			align : 'left'*/
		},{
			display : '注册时间',
			name : 'rowver',
			width : 75,
			sortable : false,
			align : 'left',
			paramcolnames : [ 'rowver' ],
			handlefunction : Enterprise.getSimpleTime
	    } ];
	},
	/**
	 * 加载查询内容
	 */
	queryEnterprise: function(){
		var areaId = $('#queryArea').combobox('getValue');
		var enterpriseName = $("#enterpriseNameSql").val();
		var platformId = $("#platform").val();
		var businessScopeId = $("#businessScopeListSql").val();
		// 查询参数
		var params = [ {
			name : 'areaId',
			value : areaId
		},{
			name : 'enterpriseName',
			value : enterpriseName
		},{
			name : 'platformId',
			value : platformId
		},{
			name : 'businessScopeId',
			value : businessScopeId
		}];

		$("#tbEnterprise").flexOptions({
			url : appCtx + "base/enterprise/loadEnterpriseList.html",
			newp : 1,// 设置起始页
			params : params
		// 设置查询参数
		}).flexReload();// 重新加载
	},
	EnterpriseListReload: function(){
		$("#tbEnterprise").flexOptions({
			url : appCtx + "base/enterprise/loadEnterpriseList.html",
		}).flexReload();
	},
	
	updateEnterprise: function(){
		//var me = this;
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,2000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,2000);
			return;
		}
		
		var url = appCtx + "base/enterprise/initUpdateEnterpriseForm.html?enterpriseId="+checkedIds[0];
		window.parent.doDataDialog("update","修改业户信息",iFrameName,"EnterpriseForm.saveEnterprise()", "Enterprise.EnterpriseListReload()",url);
	},
	
	synOwner: function(){
		//var me = this;
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要同步运政业户数据吗?",iFrameName,"Enterprise.synDataOwnerConfirm()");
	},
	
	synDataOwnerConfirm :function(){
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/enterprise/synOwnerInfo.html",
			data:{
					vehicleIds : checkedIds.toString()
				 },
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbEnterprise").flexReload();
					window.parent.global.ajaxLoading.pop('同步成功！',false,1000);
					return;
				}else if(data.code == "1"){
					window.parent.global.ajaxLoading.pop('运政无数据！',false,1000);
				}else{
					window.parent.global.ajaxLoading.pop('同步失败！',false,1000);
				}
				
	        }
	    });	
	},
	
	/**
	 * 批量删除
	 */
	delEnterprises: function(){
		//var me = this;
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要删除的数据!',false,2000);
			return;
		}
		window.parent.doConfirm("确定要删除吗？删除后将无法恢复！",iFrameName,"Enterprise.deleteEnterpriseConfirm()");
		
	},
	/**
	 * 查询详情
	 */
	queryDetailForm: function(){
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要查看的数据!',false,2000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,2000);
			return;
		}	
		var url = appCtx + "base/enterprise/initDetailInfo.html?enterpriseId="+checkedIds[0];
		window.parent.doDataDialog("detail","业户详细信息",iFrameName,"EnterpriseForm.detailConfirm()", "Enterprise.EnterpriseListReload()",url);
		
	},
	deleteEnterpriseConfirm: function(){
		var checkedIds = $("#tbEnterprise").getCheckedRows();
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/enterprise/delEnterpriseList.html",
			data:{enterpriseIds : checkedIds.toString()},
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbEnterprise").flexReload();
					window.parent.global.ajaxLoading.pop('删除成功！',false,1000);
					return;
				}else if(data.code == "1"){
					msg = "删除失败！";
				}
	        }
	    });	
	},
	exportComfirm:function(){

		var me = this;
		var p=window.parent;
		
		var options = $("#tbEnterprise").getOptions();
		//总记录数
		var total = options.total;
		//开始页数
		var StartPage=window.parent.$("#StartPageIndex").val();
		//结束页数
		var EndPage=window.parent.$("#EndPageIndex").val();
		var validate=true;
		var msg="";
		if(!StartPage || StartPage==0){
			msg+="起始页不能为空或者0";
			validate=false;
		}
		if(!EndPage || EndPage==0){
			msg+="结束页不能为空或者0";
			validate=false;
		}
		
		if(StartPage && EndPage &&EndPage<StartPage){
			msg+="结束页要大于起始页";
			validate=false;
		}
		if(!validate){
			p.ajaxLoading(msg,false,2000);
			return;
		}
		p.$('#exportModal').modal('hide');
		p.ajaxLoading("正在导出,请稍后.....",true,2000);
		//每页大小
		var pagesize = options.rp;
		
		//获取导出的参数
		var exportParams = options.exportParams;
		if((EndPage - StartPage + 1) * pagesize > 60000&&total>60000)
		{
			global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
			return
		}
		
        var column = Enterprise.getColumn();
        var exportColumns = new Array();
        for(var i=0;i<column.length;i++){
        	if(column[i].hide!=true &&column[i].name !="operation" && column[i].name !="noColor" && column[i].name !="registrationNoKindName"){
        		exportColumns.push(column[i]);
        	}
        }
		var header1 = JSON.stringify(exportColumns);
		var colModelList=new Array();//表头
		colModelList.push(header1);
		var colModel= $.toJSON(colModelList);	
		var areaId = $('#queryArea').combobox('getValue');
		var enterpriseName = $("#enterpriseNameSql").val();
		var platformId = $("#platform").val();
		var businessScopeId = $("#businessScopeListSql").val();	
		var paramsGrid =  {
				colModel:colModel,
				title:"业户信息",
				areaId: areaId,
				enterpriseName:enterpriseName,
				platformId:platformId,
				businessScopeId:businessScopeId,
				imgsrc:null,
				fromNumber:(StartPage-1)*pagesize,
				pageSize:(EndPage - StartPage + 1)*pagesize
		};
		
		post(appCtx + "base/enterprise/exportEnterprises.html",paramsGrid);
	},
	/**
	 * 导出业户信息
	 */
	exportEnterprise: function(){
		var p=window.parent;
		var options = $("#tbEnterprise").getOptions();
		var total = options.total;
		if(total==0){
			p.ajaxLoading("无导出数据",false,2000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		window.parent.$("#StartPageIndex").val(1);
		window.parent.$("#EndPageIndex").val(pages);
		window.parent.doExportModal("导出业户信息",iFrameName,"Enterprise.exportComfirm()");   
		
	},
};

